package org.example.mutithread.future;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangjg
 * @desc 4
 * @date 2023/03/28 09:03
 **/
public class F4 {

    public static void main(String[] args) {
        //当一个线程依赖另一个线程时用 thenApply 方法来把这两个线程串行化,
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            //暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("111");
            return 1024;
        }).thenApply(f -> {
            System.out.println("222");
            return f + 1;
        }).thenApply(f -> {
            //int age = 10/0; // 异常情况：哪步出错就停在哪步。
            System.out.println("333");
            return f + 1;
        }).whenCompleteAsync((v, e) -> {
            System.out.println("*****v: " + v + " e=" + e);
        }).exceptionally(e -> {
            e.printStackTrace();
            return null;
        });

        System.out.println("-----主线程SLEEP，START");

//        try {
//            System.out.println("completableFuture.get = " + completableFuture.get());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        System.out.println("completableFuture.getNow(100) = " + completableFuture.getNow(100));

        try {
            System.out.println("completableFuture.get(1,SECONDS) = " + completableFuture.get(1, TimeUnit.SECONDS));
        } catch (Exception e) {
            System.err.println("completableFuture.get(1,SECONDS) ");
            e.printStackTrace();
        }

        System.out.println("completableFuture.join = " + completableFuture.join());
        System.out.println("completableFuture.complete = " + completableFuture.complete(100));


        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("-----主线程结束，END");

    }

}
